import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

import routes from './routes'
import homeConfig from './homeConfig'
import { loadUserMenus } from '../api/index'

import { useBaseStore } from '../stores/useBaseStore'
let baseStore = null

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 用于存储动态添加的路由名称
const dynamicRoutesAdded = []

router.beforeEach(async (to, from, next) => {
  // 初始化仓库
  if (baseStore == null) {
    baseStore = useBaseStore()
  }
  // console.log(to.path)
  // 判断是否为公开路由
  if (to.meta.isPublic) {
    next()
    return
  }
  // 判断非公开页面访问是否已经登录
  if (baseStore.token == '') {
    next('/login')
    ElMessage.error({
      message: '请先登录',
    })
    return
  }
  // 判断登录用户是否具有权限访问需要跳转的页面
  if (baseStore.menus.length == 0) {
    let data = await loadUserMenus()
    baseStore.menus = data
  }
  // 检查动态路由是否已添加
  let needRedirect = false
  for (let m of baseStore.menus) {
    let path = m.right_path
    let name = path.replace(/^\/home/, '').replace(/\//g, '')
    // 判断路由是否增加过
    if (!dynamicRoutesAdded.includes(name)) {
      let component = homeConfig[path]
      router.addRoute('home', {
        path,
        name,
        component,
      })
      // 把增加的路由放到数组中用于判断
      dynamicRoutesAdded.push(name)
      // 新加路由需要重定向
      needRedirect = true
    }
  }
  // 如果需要重定向，重新访问当前路由
  if (needRedirect) {
    // 新路由需要替换操作 => 解决动态路由刷新404得问题
    next({ ...to, replace: true })
  } else {
    next()
  }
})

export default router
